﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;

namespace NJL.WebImage
{
    public partial class PutOutImage : BasePageVisitor
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadData();
            }
        }

        private void LoadData()
        {
            if (Request.QueryString["id"] != null && Request.QueryString["id"] != "" && Request.QueryString["st"] != null && Request.QueryString["st"] != "")
            {
                string strImageCode = Request.QueryString["id"];
                string strImageSizeType = Request.QueryString["st"];

                BLL.NJL_IMAGE bll = new BLL.NJL_IMAGE();
                Model.NJL_IMAGE model = bll.GetModel(strImageCode);

                if (model == null || !CheckImageIsHave(model.ID) || GetImageSize(strImageSizeType)=="")
                {
                    PutOutDefautImage();
                }
                else
                {
                    string strImageSize = GetImageSize(strImageSizeType);
                    int iWidth = Convert.ToInt32(strImageSize.Split(new string[] { "*" }, StringSplitOptions.None)[0]);
                    int iHeight = Convert.ToInt32(strImageSize.Split(new string[] { "*" }, StringSplitOptions.None)[1]);
                    CreateImage(base.GetImageLocalPath(model.ID), "", iWidth, iHeight);
                }
            }
            else
            {
                PutOutDefautImage();
            }
        }

        /// <summary>
        /// 如果没有发现图片，返回一个临时图片
        /// </summary>
        private void PutOutDefautImage()
        {
            System.Drawing.Bitmap image = new System.Drawing.Bitmap(160, 120);
            Graphics g = Graphics.FromImage(image);
            Font f = new System.Drawing.Font("微软雅黑", 16);//, System.Drawing.FontStyle.Bold);
            Brush b = new System.Drawing.SolidBrush(Color.Black);
            Brush r = new System.Drawing.SolidBrush(Color.FromArgb(166, 8, 8));

            //g.FillRectangle(new System.Drawing.SolidBrush(Color.Blue),0,0,image.Width, image.Height);
            //			g.Clear(Color.AliceBlue);//背景色
            g.Clear(System.Drawing.ColorTranslator.FromHtml("#CCCCCC"));//背景色

            g.DrawString("I'm Sorry", f, b, 35, 15);
            g.DrawString("图片没了", f, b, 35, 45);
            g.DrawString("-_-!", f, b, 60, 75);

            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            //history back 不重复 
            Response.Cache.SetNoStore();//这一句 		
            Response.ClearContent();
            Response.ContentType = "image/Jpeg";
            Response.BinaryWrite(ms.ToArray());
            g.Dispose();
            image.Dispose();
        }

        private void CreateImage(string originalImagePath, string thumbnailPath, int width, int height)
        {
            //获取原始图片  
            System.Drawing.Image originalImage = System.Drawing.Image.FromFile(originalImagePath);
            //缩略图画布宽高  
            int towidth = width;
            int toheight = height;
            //原始图片写入画布坐标和宽高(用来设置裁减溢出部分)  
            int x = 0;
            int y = 0;
            int ow = originalImage.Width;
            int oh = originalImage.Height;
            //原始图片画布,设置写入缩略图画布坐标和宽高(用来原始图片整体宽高缩放)  
            int bg_x = 0;
            int bg_y = 0;
            int bg_w = towidth;
            int bg_h = toheight;
            //倍数变量  
            double multiple = 0;
            //获取宽长的或是高长与缩略图的倍数  
            if (originalImage.Width >= originalImage.Height)
                multiple = (double)originalImage.Width / (double)width;
            else
                multiple = (double)originalImage.Height / (double)height;
            //上传的图片的宽和高小等于缩略图  
            if (ow <= width && oh <= height)
            {
                //缩略图按原始宽高  
                bg_w = originalImage.Width;
                bg_h = originalImage.Height;
                //空白部分用背景色填充  
                bg_x = Convert.ToInt32(((double)towidth - (double)ow) / 2);
                bg_y = Convert.ToInt32(((double)toheight - (double)oh) / 2);
            }
            //上传的图片的宽和高大于缩略图  
            else
            {
                //宽高按比例缩放  
                bg_w = Convert.ToInt32((double)originalImage.Width / multiple);
                bg_h = Convert.ToInt32((double)originalImage.Height / multiple);
                //空白部分用背景色填充  
                bg_y = Convert.ToInt32(((double)height - (double)bg_h) / 2);
                bg_x = Convert.ToInt32(((double)width - (double)bg_w) / 2);
            }
            //新建一个bmp图片,并设置缩略图大小.  
            System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);
            //新建一个画板  
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);
            //获取或设置绘制到此 System.Drawing.Graphics 的合成图像的呈现质量
            g.CompositingQuality = CompositingQuality.HighQuality;
            //获取或设置一个值，该值指定在呈现此 System.Drawing.Graphics 的过程中像素如何偏移
            g.PixelOffsetMode = PixelOffsetMode.HighQuality;
            //设置高质量插值法  
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            //设置高质量,低速度呈现平滑程度  
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            //清空画布并设置背景色  
            g.Clear(System.Drawing.ColorTranslator.FromHtml("#FFFFFF"));
            //在指定位置并且按指定大小绘制原图片的指定部分  
            //第一个System.Drawing.Rectangle是原图片的画布坐标和宽高,第二个是原图片写在画布上的坐标和宽高,最后一个参数是指定数值单位为像素  
            g.DrawImage(originalImage, new System.Drawing.Rectangle(bg_x, bg_y, bg_w, bg_h), new System.Drawing.Rectangle(x, y, ow, oh), System.Drawing.GraphicsUnit.Pixel);

            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            string strContentType = "image/jpeg";
            try
            {
                //获取图片类型  
                string fileExtension = System.IO.Path.GetExtension(originalImagePath).ToLower();
                //按原图片类型保存缩略图片,不按原格式图片会出现模糊,锯齿等问题.  
                switch (fileExtension)
                {
                    //case ".gif": bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Gif); break;
                    //case ".jpg": bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg); break;
                    //case ".bmp": bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Bmp); break;
                    //case ".png": bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Png); break;
                    case ".gif": bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Gif); strContentType = "image/gif"; break;
                    case ".jpg": bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); strContentType = "image/jpeg"; break;
                    case ".bmp": bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp); strContentType = "image/bmp"; break;
                    case ".png": bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Png); strContentType = "image/png"; break;
                }
            }
            catch (System.Exception e)
            {
                throw e;
            }
            finally
            {
                originalImage.Dispose();
                bitmap.Dispose();
                g.Dispose();
            }



            //history back 不重复 
            Response.Cache.SetNoStore();//这一句 		
            Response.ClearContent();
            Response.ContentType = strContentType;
            Response.BinaryWrite(ms.ToArray());
        }

        public string GetImageSize(string SizeType)
        {
            switch(SizeType.ToUpper())
            {
                case "1":
                    return "147*105";//列表尺寸：147px×105px
                case "2":
                    return "93*69";//小图：93px×69px
                case "3":
                    return "75*57";//首页滚动小图：75px×57px
                case "4":
                    return "107*77";//右侧并列图像：107px×77px 
                case "5":
                    return "500*375";//新闻详情顶部图片大小：500px×375px 
                case "6":
                    return "305*227";//商铺首页服务图片大小：305px×227px 
                case "U1":
                    return "120*90";//头像：120px×90px     67px×50px
                case "U2":
                    return "67*50";//
                case "C1":
                    return "269*202";//特色、景点： 269px×202px
                case "C2":
                    return "210*158";//企业头像： 210px×158px
                default:
                    return "";
            }
        }
    }
}